<template>
	<view :style="themeColor">
		<view class="page">
			<view class="flex benben-position-layout flex flex-wrap align-center cachVideo_flex_0"
				:style="{height:(88+StatusBarRpx)+'rpx',paddingTop:StatusBarRpx+'rpx', }">
				<view class='flex flex-wrap align-center justify-between flex-sub cachVideo_fd0_0'>
					<view class='flex flex-wrap align-center cachVideo_fd0_0_c0' @tap.stop="handleJumpDiy"
						data-type="back" data-url="1">
						<text class='fu-iconfont2  cachVideo_fd0_0_c0_c0'>&#xE794;</text>
					</view>
					<view class='flex flex-wrap align-stretch justify-center'>
						<text class='cachVideo_fd0_0_c1_c0'>缓存视频</text>
					</view>
					<view class='flex flex-wrap align-center justify-end cachVideo_fd0_0_c0'>
					</view>
				</view>

			</view>
			<view :style="{height: (88+StatusBarRpx)+'rpx'}"></view>

			<view class="loading_css" v-if="isShow">
				<u-loading size="36" color="#3090FF"></u-loading>
				<view>加载中</view>
			</view>

			<template v-else>
				<view class="tips">退出后下载中的视频需重新下载，请勿退出</view>
				<!---flex布局flex布局开始-->
				<view class="flex flex-direction flex-wrap align-stretch benben-flex-layout cachVideo_flex_1">
					<view class='flex flex-direction flex-wrap align-stretch' v-for="(item, index) in directoryList"
						:key="index">
						<view class='flex flex-wrap align-center cachVideo_fd1_0_c0'>
							<text class='cachVideo_fd1_0_c0_c0'>{{item.name}}</text>
						</view>
						<template v-if="item.children.length > 0">
							<view class='flex flex-wrap align-center cachVideo_fd1_0_c1' v-for="(v, k) in item.children"
								:key="k" @tap.stop="selectChapter(index, k)">
								<view class='flex flex-wrap align-center flex-sub'>
									<text>{{v.name}}</text>
								</view>
								<template v-if="v.is_download == 0">
									<image v-if="!v.is_start_download" class='cachVideo_fd1_0_c1_c1'
										mode="aspectFill" :src='STATIC_URL+"135.png"'></image>
									<image v-else class='cachVideo_fd1_0_c1_c1' mode="aspectFill"
										:src='STATIC_URL+"3.png"'></image>
								</template>
								<template v-if="v.is_download == 1">
									<image class='cachVideo_fd1_0_c1_c1' mode="aspectFill"
										:src='STATIC_URL+"521.png"'></image>
								</template>
								<view class="progress_view" v-if="v.is_download == 2">
									<u-circle-progress width="40" border-width="4" active-color="#3090FF"
										inactive-color="#FFFFFF" bg-color="#F8F8FA" :percent="percent">
								
									</u-circle-progress>
								</view>
							</view>
						</template>
					</view>
				</view>
				<view class="noData" v-if="directoryList.length == 0 && !isShow">
					<image :src='STATIC_URL+"no.png"'></image>
				</view>
				<!-- <view class="flex benben-flex-layout flex-wrap align-center" v-if="!selectAll" @tap.stop="selectTotal">
					<view class='flex flex-wrap align-center justify-center cachVideo_fd2_0'>
						<text>全部下载</text>
					</view>
				</view> -->

				<view class="flex benben-flex-layout flex-wrap align-center" v-if="downloadState == 0">
					<view class='flex flex-wrap align-center justify-between cachVideo_fd3_0'>
						<view v-if="selectAll" class='flex flex-wrap align-center justify-center cachVideo_fd3_0_c0' @tap.stop="close">
							<text class='cachVideo_fd3_0_c0_c0'>取消全选</text>
						</view>
						<view v-else class='flex flex-wrap align-center justify-center cachVideo_fd3_0_c0' @tap.stop="selectTotal">
							<text class='cachVideo_fd3_0_c0_c0'>全选</text>
						</view>
						<view class='flex flex-wrap align-center justify-center cachVideo_fd3_0_c1'
							@tap.stop="confirmDownload">
							<text class='cachVideo_fd3_0_c1_c0'>立即下载</text>
						</view>
					</view>
				</view>
				<view style="height: 140rpx;"></view>
			</template>
			
		</view>
	</view>
</template>
<script>
	export default {
		components: {},


		data() {
			return {
				isShow: true,
				id: "",  // 课程id
				directoryList: [],
				selectAll: true,
				one_index: -1,
				two_index: -1,
				currentIndex: 0, // 下载文件的index
				files: [], // 重新组装需要下载的文件列表
				percent: 0, // 下载文件进度
				saveFileList: [],  // 已保存的文件列表
				downloadState: 0,  // 是否在下载中
				downloadTask: null,
				back_state: 0,
			};
		},
		computed: {
			themeColor() {
				return this.$store.getters.themeColor
			},

		},
		watch: {},
		onLoad(options) {
			let {
				id
			} = options;
			if (id !== undefined) this.id = id;
			this.getCourseCatalog();
			if (uni.getStorageSync('saveFileList')) {
				this.saveFileList = uni.getStorageSync('saveFileList');
				// console.log(this.saveFileList);
			}
			
		},
		onUnload() {
			this.stopDownload();
		},
		onReady() {

		},
		onShow() {

		},
		onHide() {

		},
		onResize() {

		},
		onPullDownRefresh() {

		},
		onReachBottom(e) {

		},
		onPageScroll(e) {

		},
		methods: {
			// 课程目录  post65743c6fb43e4
			getCourseCatalog() {
				this.$api.post(global.apiUrls.post65743c6fb43e4, {
					aid: this.id
				}).then(res => {
					console.log(res);
					this.isShow = false;
					if (res.data.code == 1) {
						this.directoryList = res.data.data;
						if (this.directoryList.length > 0) {
							this.directoryList.forEach((v, k) => {
								if (v.children.length > 0) {
									v.children.forEach((v1, k1) => {
										v1.is_start_download = true;
										v1.percent = 0;
									})
								}
							})
						}
					} else {
						this.$message.info(res.data.msg);
					}
				})
			},
			// 全选
			selectTotal() {
				if (this.downloadState == 1) {
					return;
				}
				this.selectAll = true;
				if (this.directoryList.length > 0) {
					this.directoryList.forEach((v, k) => {
						if (v.children.length > 0) {
							v.children.forEach((v1, k1) => {
								v1.is_start_download = true;
							})
						}
					})
				}
			},
			// 单个选择
			selectChapter(index, k) {
				if (this.downloadState == 1) {
					return;
				}
				if (this.directoryList[index].children[k].is_download == 1) {
					return;
				}
				this.one_index = index;
				this.two_index = k;
				this.directoryList[index].children[k].is_start_download = !this.directoryList[index].children[k].is_start_download;
				let index_num = -1;
				this.directoryList.forEach((v, k) => {
					if (v.children.length > 0) {
						v.children.forEach((v1, k1) =>{
							if (!v1.is_start_download) {
								index_num = k1;
							}
						})
					}
				})
				if (index_num == -1) {
					this.selectAll = true;
				} else {
					this.selectAll = false;
				}
				this.$forceUpdate();
			},
			// 取消全选
			close() {
				this.selectAll = false;
				if (this.directoryList.length > 0) {
					this.directoryList.forEach((v, k) => {
						if (v.children.length > 0) {
							v.children.forEach((v1, k1) => {
								v1.is_start_download = false;
							})
						}
					})
				}
			},
			confirmDownload() {
				if (this.downloadState == 1) return;
				let files = [];
				if (this.directoryList.length > 0) {
					this.directoryList.forEach((v, k) => {
						if (v.children.length > 0) {
							v.children.forEach((v1, k1) => {
								if (v1.is_download == 0) {
									if (v1.is_start_download) {
										files.push({
											id: v1.aid,
											url: v1.shipin
										})
									}
								}
							})
						}
					})
				}
				if (files.length == 0) {
					this.$message.info('请选择缓存的视频');
					return;
				}
				let _this = this;
				uni.showModal({
					title: '提示',
					content: '访问您的存储权限，使用保存文件到设备功能，用于缓存视频，是否允许？',
					success: function(res) {
						if (res.confirm) {
							console.log('用户点击确定');
							_this.files = files;
							_this.downloadFile(_this.files[_this.currentIndex]);
						} else if (res.cancel) {
							console.log('用户点击取消');
						}
					},
					fail: function(err) {
						console.log(err);
					}
				})
				
			},
			downloadFile(file) {
				let _this = this;
				if (_this.directoryList.length > 0) {
					_this.directoryList.forEach((v, k) => {
						if (v.children.length > 0) {
							v.children.forEach((v1, k1) => {
								if (v1.shipin == file.url) {
									v1.is_download = 2;
								}
							})
						}
					})
					_this.$forceUpdate();
				}
				_this.downloadState = 1;
				_this.downloadTask = uni.downloadFile({
					url: file.url,
					success(res) {
						let tempFilePath = res.tempFilePath;
						// 下载成功后的处理逻辑，比如保存文件到本地
						uni.saveFile({
							tempFilePath: tempFilePath,
							success: function(res) {
								console.log(res);
								_this.addRecord(file.id, res.savedFilePath);
								// 下载完一项后，递归下载下一项
								if (_this.currentIndex < _this.files.length - 1) {
									_this.currentIndex++;
									_this.downloadFile(_this.files[_this.currentIndex]);
									_this.percent = 0;
								} else {
									_this.downloadState = 0;
									_this.$message.info('下载完成');
								}
							},
							fail: function(err) {
								// 下载失败的处理逻辑
								_this.downloadTask.abort();
								_this.downloadTask = null;
								_this.$message.info('文件保存失败，请重试');
								if (_this.directoryList.length > 0) {
									_this.directoryList.forEach((v, k) => {
										if (v.children.length > 0) {
											v.children.forEach((v1, k1) => {
												if (v1.shipin == file.url) {
													v1.is_download = 0;
												}
											})
										}
									})
								}
								_this.downloadState = 0;
								_this.$forceUpdate();
							}
						});

					},
					fail(res) {
						// 下载失败的处理逻辑
						_this.downloadTask.abort();
						_this.downloadTask = null;
						if (_this.back_state == 0) {
							_this.$message.info('下载失败，请重试');
						}
					}
				});
				_this.downloadTask.onProgressUpdate((res) => {
					if (res.progress < 50) {
						_this.percent = 50;
					} else if (res.progress == 80) {
						_this.percent = 80;
					} else if (res.progress == 100) {
						_this.percent = 100;
					}
					// _this.directoryList[_this.one_index].children[_this.two_index].percent = res.progress;
					// console.log('下载进度' + res.progress);
					// console.log('已经下载的数据长度' + res.totalBytesWritten);
					// console.log('预期需要下载的数据总长度' + res.totalBytesExpectedToWrite);
					_this.$forceUpdate();
				});
			},
			stopDownload() {
				this.back_state = 1;
				this.downloadTask.abort();
				this.downloadTask = null;
			},
			// 添加学习记录  post65858063aa5e8
			addRecord(id, url) {
				this.$api.post(global.apiUrls.post65858063aa5e8, {
					chapter_id: id
				}).then(res => {
					// console.log(res);
					if (res.data.code == 1) {
						if (this.directoryList.length > 0) {
							this.directoryList.forEach((v, k) => {
								if (v.children.length > 0) {
									v.children.forEach((v1, k1) => {
										if (v1.aid == id) {
											v1.is_download = 1;
										}
									})
								}
							})
						}
						this.saveFileList.push({
							id: id,
							url: url,
							course_id: this.id
						})
						uni.setStorageSync('saveFileList', this.saveFileList);
						this.$forceUpdate();
					} else {
						this.$message.info(res.data.msg);
					}
				})
			},

		}
	};
</script>
<style lang="scss" scoped>
	.tips {
		padding: 24rpx 32rpx;
		color: #999;
		font-size: 24rpx;
	}

	.page {
		width: 100vw;
		overflow-x: hidden;
		min-height: calc(100vh - var(--window-bottom));
		background: #FFFFFF;
		background-size: 100% auto;
	}

	.cachVideo_flex_0 {
		background: #fff;
		width: 750rpx;
		height: 88rpx;
		overflow: hidden;
		z-index: 10;
		top: 0rpx;
		background-size: 100% auto !important;
	}

	.cachVideo_fd0_0_c1_c0 {
		font-size: 36rpx;
		font-weight: 700;
		color: #333333;
		line-height: 50rpx;
	}

	.cachVideo_fd0_0_c0_c0 {
		font-size: 36rpx;
		color: #333;
	}

	.cachVideo_fd0_0_c0 {
		width: 120rpx;
	}

	.cachVideo_fd0_0 {
		padding: 0rpx 32rpx 0rpx 32rpx;
	}

	.cachVideo_flex_1 {
		padding: 0rpx 40rpx 0rpx 40rpx;
	}

	.cachVideo_fd1_0_c1_c1 {
		width: 40rpx;
		height: 40rpx;
		border-radius: 0rpx 0rpx 0rpx 0rpx;
	}

	.progress_view {
		width: 40rpx;
		height: 40rpx;
	}

	.cachVideo_fd1_0_c1 {
		background: #F8F8FA;
		background-size: 100% auto;
		padding: 24rpx;
		border-radius: 16rpx;
		margin: 20rpx 0rpx 0rpx 0rpx;
	}

	.cachVideo_fd1_0_c0_c0 {
		font-size: 32rpx;
		color: rgba(51, 51, 51, 1);
		font-weight: 700;
	}

	.cachVideo_fd1_0_c0 {
		margin: 24rpx 0rpx 4rpx 0rpx;
	}

	.cachVideo_fd2_0 {
		background: var(--benbenbgColor0);
		background-size: 100% auto;
		border-radius: 8rpx;
		color: var(--benbenFontColor3);
		font-size: 32rpx;
		line-height: 88rpx;
		height: 88rpx;
		width: 690rpx;
		position: fixed;
		bottom: calc(48rpx + var(--window-bottom));
		left: 30rpx;
		z-index: 20;
	}

	.cachVideo_fd3_0_c1_c0 {
		font-size: 30rpx;
		color: var(--benbenFontColor3);
	}

	.cachVideo_fd3_0_c1 {
		border: 1px solid var(--benbenbdColor0);
		background: var(--benbenbgColor0);
		border-radius: 12rpx;
		line-height: 80rpx;
		width: 315rpx;
		height: 80rpx;
		background-size: 100% auto;
	}

	.cachVideo_fd3_0_c0_c0 {
		font-size: 30rpx;
		color: rgba(167, 166, 167, 1);
	}

	.cachVideo_fd3_0_c0 {
		border: 1px solid rgba(167, 166, 167, 1);
		width: 315rpx;
		height: 80rpx;
		border-radius: 12rpx;
	}

	.cachVideo_fd3_0 {
		margin: 0rpx 40rpx 0rpx 40rpx;
		width: 670rpx;
		height: 80rpx;
		position: fixed;
		bottom: calc(48rpx + var(--window-bottom));
		z-index: 20;
		background: #FFFFFF;
	}
</style>